package com.aircraft.config.aspect;

import com.aircraft.common.annotation.AccessLimit;
import com.aircraft.config.redis.RedisService;
import com.aircraft.domain.vo.R;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 访问拦截器
 */
@Component
@Slf4j
public class AccessLimitInterceptor implements HandlerInterceptor {
    @Resource
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {// Handler 是否为 HandlerMethod 实例
            if (handler instanceof HandlerMethod) {
                // 强转
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                // 获取方法
                Method method = handlerMethod.getMethod();
                // 是否有AccessLimit注解
                if (!method.isAnnotationPresent(AccessLimit.class)) {
                    return true;
                }
                // 获取注解内容信息
                AccessLimit accessLimit = method.getAnnotation(AccessLimit.class);
                if (accessLimit == null) {
                    return true;
                }
                Long seconds = (long) accessLimit.second();
                int maxCount = accessLimit.maxCount();
                // 存储key
                String key = request.getRemoteAddr() + ":" + request.getContextPath() + ":" + request.getServletPath();
                // 已经访问的次数
                Integer count = redisService.getCacheObject(key);
                if (null == count || -1 == count) {
                    redisService.setCacheObject(key, 1, seconds, TimeUnit.SECONDS);
                    return true;
                }
                if (count < maxCount) {
                    redisService.increment(key);
                    return true;
                }
                if (count >= maxCount) {
                    log.warn("请求过于频繁请稍后再试");
                    writer(response,"请求过于频繁请稍后再试",505);
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            log.warn("请求过于频繁请稍后再试");
            writer(response,"请求过于频繁请稍后再试",505);
            e.printStackTrace();
        }
        return true;
    }

    private static void writer(HttpServletResponse response,String msg,Integer code) throws Exception{
        response.setContentType("application/json;charset = UTF-8");
        response.getWriter().write(JSON.toJSONString(R.fail(code,msg)));
    }
}